package com.zx.mes.hyl.security.core.authorize.impl;

import com.zx.mes.hyl.security.core.authorize.AuthorizeConfigManager;
import com.zx.mes.hyl.security.core.authorize.AuthorizeConfigProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 默认的授权配置管理器
 * @author huayunlong
 * @date 2018-6-3
 */
@Component
public class LongAuthorizeConfigManage implements AuthorizeConfigManager {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private List<AuthorizeConfigProvider> authorizeConfigProviders;

    @Override
    public void config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
        boolean existAnyRequestConfig=false;
        String existAnyRequestConfigName=null;
        /* 只允许配置一次,如有多个配置抛异常 **/
        for (AuthorizeConfigProvider authorizeConfigProvider:authorizeConfigProviders) {
            boolean currentIsAnyRequestConfig=authorizeConfigProvider.config(config);

            if (existAnyRequestConfig && currentIsAnyRequestConfig){
                logger.info("重复的anyRequest配置");
                throw new RuntimeException("重复的anyRequest配置:" + existAnyRequestConfigName + ","
                        + authorizeConfigProvider.getClass().getSimpleName());
            } else if (currentIsAnyRequestConfig) {
                existAnyRequestConfig = true;
                existAnyRequestConfigName = authorizeConfigProvider.getClass().getSimpleName();
            }
        }

        /* 如果没有配置,那么加上此句 **/
        if(!existAnyRequestConfig){
            config.anyRequest().authenticated();
        }
    }
}
